package com.spring.security.config;

import com.spring.security.service.CumDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * ClassName: SecurityConfiguration
 * Desc:
 * Date： 2017/5/26
 * Created：shaom
 */
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService() {
        return new CumDetailsService();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
//        auth.inMemoryAuthentication().withUser("bill").password("bill").roles("USER");
//        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
//        auth.inMemoryAuthentication().withUser("dba").password("dba").roles("ADMIN", "DBA");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resource/**", "/js/**", "/css/**", "/images/**", "/**/favicon.ico");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
//                .antMatchers("/resources/**").permitAll()
                .anyRequest().authenticated()//所有请求需要认证即登录后才能访问
                .and().formLogin()
                .loginPage("/login")
                .failureForwardUrl("/login?error")//如果用户身份认证失败,页面就重定向到 /login?error
                .permitAll()
                .defaultSuccessUrl("/", true)//定制登录行为，登录页面可任意访问
                .and()
                .logout().permitAll();//定制注销行为，注销请求可任意访问
    }
}